<?php
/**
 * @author all@cosmos-framework.org
 * @copyright (c) 2013 cosmos-framework.org
 * @license http://www.opensource.org/licenses/mit-license.php
 * @link http://cosmos-framework.org/
 * @package cosmos.framework
 * @version 2.0
 */
namespace Cosmos;

class Server {

    private $_sock;

    /**
     * @param string $sock
     */
    public function __construct($sock = 'tcp://0.0.0.0:8000') {

        $this->_sock = $sock;
    }

    /**
     * @param resource & $connect
     * @return string
     */
    public static function read(&$connect) {

        return ($c = fread($connect, 8192)) ? $c . self::read($connect) : '';
    }

    /**
     * stop command is /stop.
     */
    public function run() {

        // response handle.
        $p = $this->_open($no, $err) ? : trigger_error($no . ': ' . $err, E_USER_ERROR);

        while (1) {
            // yield response.
            if ($connect = @stream_socket_accept($p)) {
                switch ($message = self::read($connect)) {
                    case '/stop' :
                        break 2;

                    default :
                        $this->block($connect, $message);
                }
            }
        }

        fclose($p);
    }

    /**
     * stop command.
     */
    public function stop() {

        if ($p = fsockopen($this->_sock)) {

            // send command.
            fwrite($p, '/stop');
            fclose($p);
        }
    }

    /**
     * @param resource & $connect
     * @param string $message
     */
    protected function block(&$connect, $message) {

        echo stream_socket_get_name($connect, true), " " . $message . PHP_EOL;
    }

    /**
     * @access private
     */
    private function _open(&$no, &$err) {

        return stream_socket_server($this->_sock, $no, $err);
    }

}
